<?php


namespace app\admin\controller\v1;


use app\admin\model\TagModel;
use app\admin\Validate\tag\AddTagValidate;
use app\admin\Validate\tag\TagListByPageValidate;
use app\admin\Validate\tag\UpdateTagValidate;
use app\BaseController;
use app\common\Token;
use think\facade\Env;

class Tag extends BaseController
{
    public function getIconUrlAttr($value)
    {
        if(filter_var($value, FILTER_VALIDATE_URL)) {
            return $value;
        }
        $imageBaseUrl = Env::get('qiniu.base_url');
        return $imageBaseUrl.$value;
    }

    /**
     * 添加Tag
     * @return \think\response\Json
     */
    public function addTag() {
        Token::checkToken($this->request);
        $param = (new AddTagValidate)->validateParam();
        $model = new TagModel();
        $result = $model->save([
            "tag_name" => $param["tag_name"],
            "tag_color" => $param["tag_color"],
            "status" => $param["status"],
            "icon_url" => $param["icon_url"],
            "add_time" => getDateTime(),
        ]);
        if ($result) {
            return successJson($result, "添加成功");
        }
        return errorJson(60001, "添加失败");
    }

    /**
     * 获取分页
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getAllTag() {
        Token::checkToken($this->request);
        $param = (new TagListByPageValidate())->validateParam();
        $model = new TagModel();
        $re = $model->toPaginate($param, []);
        return successJson($re);
    }

    /**
     * 获取所有的Tag
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTags() {
        Token::checkToken($this->request);
        $model = new TagModel();
        $re = $model->where('status', '=', 1)->select();
        return successJson($re);
    }

    /**
     * 更新数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateTag() {
        Token::checkToken($this->request);
        $param = (new UpdateTagValidate())->validateParam();
        $model = new TagModel();
        $re = $model->find($param['id'])
            ->save($param);
        if($re){
            return successJson(true);
        }
        return errorJson(60004,"更新失败");
    }

    /**
     * 删除Tag
     * @param int $id
     * @return \think\response\Json
     */
    public function deleteTag(int $id) {
        Token::checkToken($this->request);
        $success = TagModel::destroy($id);
        if($success){
            return successJson(true);
        }
        return errorJson(60004,"删除失败");
    }
}